﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace DoNet.Utils
{
    /// <summary>
    /// 可以检测域名是否能够访问
    /// </summary>
    public class DomainUtil
    {
        private static ManualResetEvent TimeoutObject = new ManualResetEvent(false);

        /// <summary> 
        /// Socket连接请求       
        /// </summary>     
        ///<param name="remoteEndPoint">网络端点</param>      
        ///<param name="timeoutMSec">超时时间</param> 
        public static bool Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
        {
            TimeoutObject.Reset();
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.BeginConnect(remoteEndPoint, CallBackMethod, socket);
            //阻塞当前线程           
            if (TimeoutObject.WaitOne(timeoutMSec, false))
            {
                //MessageBox.Show("网络正常");
                //Console.WriteLine("网络正常");
                return true;
            }
            else
            {
                //MessageBox.Show("连接超时");
                //Console.WriteLine("连接超时");
                return false;
            }
        }

        //--异步回调方法       
        private static void CallBackMethod(IAsyncResult asyncresult)
        {
            //使阻塞的线程继续        
            TimeoutObject.Set();
        }

        private delegate string ConnectSocketDelegate(IPEndPoint ipep, Socket sock);
        private string ConnectSocket(IPEndPoint ipep, Socket sock)
        {
            string exmessage = "";
            try
            {
                sock.Connect(ipep);
            }
            catch (Exception ex)
            {
                exmessage = ex.Message;
            }
            finally
            {
            }

            return exmessage;
        }

        public static string GetDomainIP(string domain)
        {
            string result = "";
            try
            {
                IPHostEntry host = Dns.GetHostEntry(domain);//域名解析的IP地址
                IPAddress ip = host.AddressList[0];
                result = ip.ToString();
            }
            catch
            {
                //请检查是否正确的域名,或者您的电脑有没有联互联网
            }
            return result;
        }

        /// <summary>
        /// 获取可以连接通的域名名称（纯域名名称 不带http://和https://）
        /// </summary>
        /// <param name="domainArray">域名数组（纯域名名称 不带http://和https://）</param>
        /// <returns></returns>
        public static string GetDomainConnect(string[] domainArray)
        {
            string result = "";
            foreach (var domain in domainArray)
            {
                string domainIP = GetDomainIP(domain);
                if (!string.IsNullOrEmpty(domainIP))
                {
                    IPAddress ip = IPAddress.Parse(domainIP);
                    IPEndPoint ipep = new IPEndPoint(ip, 80);//IP和端口

                    var isCon = Connect(ipep, 6000);
                    if (isCon)
                    {
                        result = domain;
                        break;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 组合API连接url
        /// </summary>
        /// <param name="domain">域名名称（纯域名名称 不带http://和//）</param>
        /// <param name="url">域名后面的url连接字符串 /v3/certificates</param>
        /// <param name="isHttps"> http / https</param>
        /// <returns></returns>
        public static string GetDomainName(string domain, string url, bool isHttps = true)
        {
            return (isHttps ? "https" : "http") + "://" + domain + url;
        }
    }
}
